package com.cloudfun.campusshare.device.protocol.handler;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Created by Huqin on 2020/4/9
 */
@Slf4j
@Component
public class AliyunDeviceIccidMsgHandler implements AliyunIotMsgHandler {

    @Autowired
    private DeviceService deviceService;

    @Override
    public boolean support(Message message) throws JMSException {
        // TODO 修改为iccid
        return message.getStringProperty("topic").endsWith("user/simcard");
    }

    @Override
    public void handle(Message message) throws JMSException {
        this.doHandle(message);
    }

    private void doHandle(Message message) throws JMSException {
        String topic = message.getStringProperty("topic");
        String messageId = message.getStringProperty("messageId");
        String[] split = topic.split("/");
        String deviceName = split[2];
        String iccid = new String(message.getBody(byte[].class)).trim();
        boolean processSuccess = false;
        for (int i = 0; i < 5; i++) {
            try {
                deviceService.updateDeviceIccid(deviceName, iccid);
                processSuccess = true;
                break;
            } catch (ObjectOptimisticLockingFailureException oplfe) {
                log.error("4G设备iccid消息id：{}, iccid: {}, 处理时乐观锁异常: ", messageId, iccid, oplfe);
            }
        }
        if (!processSuccess) {
            throw new BusinessException(Code.ERROR, "乐观锁失败，且超过最大重试次数：" + 5);
        }
    }
}
